import {Component, OnDestroy, OnInit} from '@angular/core';
import {DataStorageUtil} from "../../util/data-storage-util";
import {AppConstants, MsgConstants} from '../../constants/constants';
import {OnlineService} from '../../services/online.service';
import {ResponseUtil} from '../../util/response-util';
import {MsgResult} from '../../models/msg-result';
import {OneDialogService} from '../../widgets/one-dialog/one-dialog.service';
import {AppConfig} from '../../app.config';
import {MsgSubscribeService, SubscribeConstants} from '../../tools/msgSubscribe/msg-subscribe.service';
import {AlarmSubject} from '../../util/alarm-subject';

declare var $;

@Component({
  selector: 'app-embedded',
  templateUrl: './embedded.component.html',
  styleUrls: ['./embedded.component.css']
})
export class EmbeddedComponent implements OnInit, OnDestroy {
  myName;
  subConstants: SubscribeConstants;
  warnInfoArr: Array<any> = [];
  constructor(
    private dataStorage: DataStorageUtil,
    private onlineService: OnlineService,
    private responseUtil: ResponseUtil,
    private dialogService: OneDialogService,
    private msgSubscribeService: MsgSubscribeService,
    private alarmSubject: AlarmSubject
  ) {
    this.initObject();
  }

  ngOnInit() {
    this.changeTheme();
    this.subscribeData();
  }
  ngOnDestroy() {
    this.msgSubscribeService.unsubscribe();
    this.subConstants.dataSubject.unsubscribe();
  }
  changeTheme() {
    const theme = this.dataStorage.get(AppConstants.theme);
    $('body').removeClass().addClass('skin-' + theme + ' sidebar-mini');
  }
  initObject() {
    this.subConstants = new SubscribeConstants();
  }
  /**
   * 调用消息推送
   */
  subscribeData() {
    if ( AppConfig.enableMsgSubscribe ) {
      this.onlineService.getAccountName()
        .subscribe(
          result => this.responseUtil.success(result, () => {
            if (result && result.code === MsgConstants.MSG_CODE_OK) {
              this.myName = result.data;
              this.subConstants.url = '/queue/' + this.myName;
              this.subConstants.dataSubject = this.alarmSubject;
              this.subConstants.isSingle = false;
              this.subConstants.isAck = true;
              this.msgSubscribeService.subscribe(this.subConstants);
              console.log('aa');
              this.ngSubscribe();
            }
            if (result && result.code !== MsgConstants.MSG_CODE_OK) {
              this.dialogService.info(result.message);
            }
          }),
          error => this.responseUtil.error(error)
        );
    }
  }
  //  angular订阅
  ngSubscribe() {
    this.subConstants.dataSubject.subscribeData().subscribe(
      (data) => {
        this.warnInfoArr = data;
      })
  }
}
